/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.fzhucc.modules.dawei.service;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.nacos.shaded.com.google.gson.Gson;
import com.fzhucc.exception.BadRequestException;
import com.fzhucc.modules.dawei.dto.DaweiKeyDto;
import com.fzhucc.modules.dawei.dto.DaweiRespDto;
import com.fzhucc.modules.dawei.dto.DaweiRespTokenDto;
import com.fzhucc.modules.dawei.dto.DaweiTokenJumpDto;
import com.fzhucc.modules.expert.domain.Expert;
import com.fzhucc.modules.system.domain.User;
import com.fzhucc.modules.system.repository.UserRepository;
import com.fzhucc.utils.AESUtil;
import com.fzhucc.utils.CreateSecrteKey;
import com.fzhucc.utils.RsaUtils2;
import com.fzhucc.utils.SecurityUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.*;


/**
 * @author yyg
 * @website https://eladmin.vip
 * @description 大为服务接口
 * @date 2023-11-07
 **/
@Service
@RequiredArgsConstructor
public class DaweiService {

    @Value("${dawei.loginUrl}")
    public String url;

    @Value("${dawei.jump}")
    public String jump;

    @Value("${dawei.merchantPrivateKey}")
    public String merchantPrivateKey;

    @Value("${dawei.gatewayPublicKey}")
    public String gatewayPublicKey;

    @Value("${dawei.merchantId}")
    public String merchantId;

    @Value("${dawei.orgId}")
    public String orgId;

    private final UserRepository userRepository;

    public DaweiKeyDto getKey() throws Exception {
        Map<String, Object> map;
        map = CreateSecrteKey.initKey();
        String gatewayPublicKey = CreateSecrteKey.getPublicKey(map);//公钥
        String merchantPrivateKey = CreateSecrteKey.getPrivateKey(map);//私钥
        DaweiKeyDto daweiKeyDto = new DaweiKeyDto();
        daweiKeyDto.setPrivateKey(merchantPrivateKey);
        daweiKeyDto.setPuclicKey(gatewayPublicKey);
        return daweiKeyDto;
    }

    public DaweiTokenJumpDto getTokenWithUrl() {
        String loginJson = "";
        //根据登录用户注册信息
        Long userId = SecurityUtils.getCurrentUserId();
        Optional<User> userRes = userRepository.findById(userId);
        if (!userRes.isPresent()) {
            throw new BadRequestException("未获取到登录信息");
        }
        User user = userRes.get();
        String username = user.getUsername();
        String nickName = user.getNickName();
        String userAccount = username + "@hy.com";//固定后缀

        String myName = "";
        if (nickName != null && !nickName.equals("")) {
            myName = nickName;
        } else {
            myName = username;
        }
        String phone = user.getPhone();
        String company = "";
        //String email = user.getEmail();
        /*if (email != null && !email.equals("")) {
            loginJson = "{\"userAccount\":\"" + userAccount + "\",\"name\":\"" + myName + "\",\"company\":\"" + company + "\",\"areacode\":\"86\",\"mobilephone\":\"" + phone + "\",\"email\":\"" + email + "\",\"password\":\"123123\",\"orgId\":\"" + orgId + "\"}";
        }else{
            loginJson = "{\"userAccount\":\"" + userAccount + "\",\"name\":\"" + myName + "\",\"company\":\"" + company + "\",\"areacode\":\"86\",\"mobilephone\":\"" + phone + "\",\"password\":\"123123\",\"orgId\":\"" + orgId + "\"}";
        }*/


        loginJson = "{\"userAccount\":\"" + userAccount + "\",\"name\":\"" + myName + "\",\"company\":\"" + company + "\",\"areacode\":\"86\",\"mobilephone\":\"" + phone + "\",\"password\":\"123123\",\"orgId\":\"" + orgId + "\"}";

        Map param = encodeParam(merchantPrivateKey, gatewayPublicKey, loginJson);
        String sign = param.get("sign").toString();
        String keyPass = param.get("keyPass").toString();

        HttpResponse response = HttpRequest.post(url)
                //业务参数签名
                .header("sign", sign)
                //Rsa加密key
                .header("keyPass", keyPass)
                // 商户号
                .header("merchantId", merchantId)
                //请求参数
                .body(param.get("data").toString())
                .execute();
        String respbody = response.body();
        Gson gson = new Gson();
        DaweiRespDto daweiRespDto = gson.fromJson(respbody, DaweiRespDto.class);
        String code = daweiRespDto.getCode();
        if (code == null || !code.equals("0")) {
            throw new BadRequestException(respbody);
        }
        String data = daweiRespDto.getData();
        //从response中获取签名信息
        Map<String, List<String>> headers = response.headers();
        if (headers == null || headers.size() < 0) {
            throw new BadRequestException("responseHeader为null");
        }
        List<String> signs = headers.get("sign");
        List<String> keyPasss = headers.get("keyPass");
        if (signs == null || signs.size() < 0) {
            throw new BadRequestException("response Sign为null");
        }
        if (keyPasss == null || keyPasss.size() < 0) {
            throw new BadRequestException("response keyPass为null");
        }
        String res = decryptParam(merchantPrivateKey, gatewayPublicKey, signs.get(0), data, keyPasss.get(0));//解密
        if (res == null || res.equals("")) {
            throw new BadRequestException("验签失败");
        }
        Gson gson2 = new Gson();
        DaweiRespTokenDto daweiRespTokenDto = gson2.fromJson(res, DaweiRespTokenDto.class);

        DaweiTokenJumpDto daweiTokenJumpDto = new DaweiTokenJumpDto();
        daweiTokenJumpDto.setToken(daweiRespTokenDto.getToken());
        daweiTokenJumpDto.setUrl(jump + daweiRespTokenDto.getToken());
        return daweiTokenJumpDto;
    }


    public static Map encodeParam(String merchantPrivateKey, String gatewayPublicKey, String data) {
        String keyPass = AESUtil.genAesSecret();
        String encodeData = AESUtil.encodeString(data, keyPass);
        String sign = RsaUtils2.sign(merchantPrivateKey, data);
        keyPass = RsaUtils2.encrypt(gatewayPublicKey, keyPass);
        String finalKeyPass = keyPass;
        HashMap hashMap = new HashMap() {{
            put("data", encodeData);
            put("keyPass", finalKeyPass);
            put("sign", sign);
        }};
        return hashMap;
    }

    public static String decryptParam(String merchantPrivateKey, String gatewayPublicKey, String sign, String data, String keyPass) {
        String decryptKeyPass, decryptData;
        try {
            decryptKeyPass = RsaUtils2.decrypt(merchantPrivateKey, keyPass);
            decryptData = AESUtil.decrypt(data, decryptKeyPass);
            String a = "A";
        } catch (RuntimeException e) {
            return "解密失败";
        }
        boolean verify = RsaUtils2.verify(gatewayPublicKey, decryptData, sign);
        if (!verify) {
            return "验签失败";
        } else {
            return decryptData;
        }
    }
}